package com.ronan.imserver.processor;

import com.ronan.common.constant.Constants;
import com.ronan.common.proto.Heart;
import com.ronan.common.protocol.RIMHeader;
import com.ronan.common.protocol.RIMProtocol;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

/**
 * FileName    : com.ronan.imserver.processor
 * Description :
 *
 * @author : ronan
 * @version : 1.0
 * Create Date : 2021/2/26 11:05
 **/
@Slf4j
public class HeartProcessor implements RIMProcessor<Heart> {
    @Override
    public void process(Heart heart, Channel channel) {

        long pingTime = heart.getHeartTime();
        log.info("服务端收[{}]到心跳, {} ms", channel.remoteAddress(), pingTime);

        long pongTime = System.currentTimeMillis();
        // 收到客户端的心跳,向客户端发送pong信息
        RIMProtocol protocol = new RIMProtocol();
        Heart pong = Heart.newBuilder().setHeartTime(pongTime).build();
        protocol.setBody(pong);
        RIMHeader header = new RIMHeader();
        header.setLength(pong.toByteArray().length);
        header.setCommand(Constants.MsgConstant.HEART);
        protocol.setHeader(header);

        log.info("服务端向客户端[{}]发送心跳消息[{}]", channel.remoteAddress(), protocol);
        channel.writeAndFlush(protocol).addListener(future -> {
            if (!future.isSuccess()) {
                log.error("消息发送失败,关闭通道!");
                channel.close();
            }
        });
    }
}
